package com.business.leaf.core.segment.domain.entity;

import com.business.leaf.core.segment.domain.valobj.Segment;
import lombok.Builder;
import lombok.Data;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName SegmentBuffer
 * @Description 缓存对象
 * @Author lgh
 * @Date 2020-04-08 16:15
 */
@Data
public class SegmentBuffer {

    /**
     * 标注是哪个业务的Tag
     */
    private String bigTag;

    private int currentPos=0;

    private boolean isInit=false;

    /**
     * 号段范围
     */
    private int step;

    /**
     * 最小的号段范围
     */
    private int minStep;

    /**
     * 缓存内容
     */
    private Segment[] segments;

    /**
     * 读写锁
     */
    private ReadWriteLock lock;

    /**
     * 下个数据是否准备好
     */
    private boolean nextReady;

    /**
     *
     */
    private AtomicBoolean threadRunning; //线程是否在运行中


    public SegmentBuffer(String bigTag) {
        this.bigTag=bigTag;
        segments=new Segment[]{new Segment(this,bigTag),new Segment(this,bigTag)};
        lock=new ReentrantReadWriteLock();
        threadRunning=new AtomicBoolean(false);
        nextReady=false;
    }

    /**
     * 获取当前的Segment
     * @return
     */
    public Segment getCurrentSegment(){
        return segments[currentPos];
    }

    public int nextPos() {
        return (currentPos + 1) % 2;
    }

    public void switchPos() {
        currentPos = nextPos();
    }

    @Override
    public String toString() {
        return "SegmentBuffer{" +
                "bigTag='" + bigTag + '\'' +
                ", currentPos=" + currentPos +
                ", isInit=" + isInit +
                ", step=" + step +
                ", minStep=" + minStep +
                ", lock=" + lock +
                ", nextReady=" + nextReady +
                ", threadRunning=" + threadRunning +
                '}';
    }
}
